package com.gragra.synchUtil;
import java.util.Iterator;
/**
 * This is a synchronized wrapper for the a standard iterator this is thread safe as
 * long as the wrapped Iterator is not changed externally
 * @author Christoph Teichmann
 * @version 0.1
 */
public class SynchronizedIterator<E> implements Iterator<E>
{
	/**
	 * the iterator on which this synchronized wrapper is based
	 */
	private final Iterator<E> base;
	/**
	 * this object is used for synchronization purposes
	 */
	private final Object synch = new Object();
	/**
	 * constructs a new SynchronizedIterator on top of the given Iterator
	 * @param base
	 */
	public SynchronizedIterator(final Iterator<E> base)
	{this.base = base;}
	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	@Override
	public boolean hasNext()
	{
		boolean b = false;
		synchronized(synch)
		{b = base.hasNext();}
		return b;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	@Override
	public E next()
	{
		synchronized(synch)
		{return base.next();}
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#remove()
	 */
	@Override
	public void remove()
	{
		synchronized(synch)
		{base.remove();}
	}
	/**
	 * returns the next Value of the Iterator if there still is any otherwise null is
	 * returned. this method is synchronized
	 * @return
	 */
	public E nextIfHas()
	{
		synchronized(synch)
		{
			if(base.hasNext())
			{return base.next();}
			else
			{return null;}
		}
	}
}